package cn.xspace.wnx.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.HeadShowUtil;
import com.xspace.android.xafcommon.util.LogUtil;

import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import com.xspace.android.xafcommon.view.RoundAngleImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.xspace.wnx.R;
import cn.xspace.wnx.entity.Body;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.library.bean.Type;

/**
 * Created by liuchen on 2016/10/11.
 */

public class MessageListAdapter extends BaseAdapter {
    private static final String TAG = "MessageListAdapter";
    private static Context mContext;
    private List<MessageEntity> dataList;
    private static String user_logo = "";

    public MessageListAdapter(Context context, List<MessageEntity> dataList) {
        super();
        this.mContext = context;
        user_logo = MyInfoUtil.getMyLogo(mContext);
        this.dataList = dataList;
        Log.d(TAG, "MessageListAdapter() called with: context = [" + context + "], dataList = [" + dataList.size() +
                "]");
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public int getViewTypeCount() {
        return super.getViewTypeCount();
    }

    @Override
    public boolean isEmpty() {
        return super.isEmpty();
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        Log.d(TAG, "getView() called with: i = [" + i + "], convertView = [" + convertView + "], viewGroup = [" +
                viewGroup + "]");
        MessageViewHolder viewHolder;
        MessageEntity messageEntity = dataList.get(i);
        if (convertView == null) {
            viewHolder = new MessageViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_message, null);
            viewHolder.findView(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (MessageViewHolder) convertView.getTag();
        }
        viewHolder.setData(viewHolder, messageEntity);
        return convertView;
    }

    /**
     * 局部刷新
     *
     * @param view
     * @param itemIndex
     */
    public void updateItem(View view, int itemIndex) {
        if (view == null) {
            return;
        }
        //从view中取得holder
        MessageViewHolder holder = (MessageViewHolder) view.getTag();
        holder.setData(holder, getItem(itemIndex));
    }

    @Override
    public long getItemId(int i) {
        return Long.parseLong(TextUtils.isEmpty(dataList.get(i).inserttime) ? "0" : dataList.get(i).inserttime);
    }

    @Override
    public MessageEntity getItem(int i) {
        return dataList.get(i);
    }

    @Override
    public int getCount() {
        return dataList.size();
    }

    public static class MessageViewHolder {
        ImageView logoIv;
        TextView unreadTv;
        TextView titleTv;
        TextView contentTv;
        TextView timeTv;
        ImageView excuseIv;
        ImageView statusIv;
        RelativeLayout relative_bg;

        public void findView(View v) {
            this.logoIv = (RoundAngleImageView) v.findViewById(R.id.imageview_head);
            this.unreadTv = (TextView) v.findViewById(R.id.tv_unreadcount);
            this.titleTv = (TextView) v.findViewById(R.id.tv_title);
            this.contentTv = (TextView) v.findViewById(R.id.tv_content);
            this.timeTv = (TextView) v.findViewById(R.id.tv_time);
            this.excuseIv = (ImageView) v.findViewById(R.id.imageview_excuse);
            this.statusIv = (ImageView) v.findViewById(R.id.msg_status);
            this.relative_bg = (RelativeLayout) v.findViewById(R.id.relative_bg);
        }

        public void setData(MessageViewHolder viewHolder, MessageEntity messageEntity) {
            //0：通知公告；1：微农信；2：单聊；3：群聊
            if (messageEntity.msg_type == 0) {
                logoIv.setImageResource(R.drawable.icon_gonggao);
                titleTv.setText(R.string.notice_tell);
                contentTv.setText(messageEntity.msg_content);
            } else if (messageEntity.msg_type == 1) {
                logoIv.setImageResource(R.drawable.icon_weinongxin);
                titleTv.setText(R.string.weinongxin);
                contentTv.setText(messageEntity.msg_content);
            } else if (messageEntity.msg_type == 2) { //单聊头像显示
                HeadShowUtil.headShow(mContext, messageEntity.msg_logo, messageEntity.user_sex, viewHolder.logoIv,
                        HeadShowUtil.HeadType.UserLogo);
            } else if (messageEntity.msg_type == 3) {
                if (messageEntity.group_type == Type.GroupType.MANAGER) { //群组类型是群组助手专用的字段
                    logoIv.setImageResource(R.drawable.group_manager);
                    titleTv.setText(R.string.group_manager);
                    contentTv.setText(messageEntity.msg_content);
                } else {
                    //头像显示
                    if (!TextUtils.isEmpty(messageEntity.msg_logo)) {
                        Picasso.with(mContext)
                                .load(messageEntity.msg_logo)
                                .placeholder(R.drawable.icon_header_default)
                                .error(R.drawable.icon_header_default)
                                .into(viewHolder.logoIv);
                    } else {
                        viewHolder.logoIv.setImageResource(R.drawable.icon_header_default);
                    }
                }
            }

            //未读消息数量
            LogUtil.d(TAG, "unread count >>" + messageEntity.msg_unread_count);
            if (messageEntity.msg_unread_count == 0) {
                viewHolder.unreadTv.setVisibility(View.GONE);
            } else {
                if (messageEntity.msg_type == MsgType.WNX_MSG.toNumber() | ////微农信的直接显示小红点
                        messageEntity.msg_warn_status == MessageEntity.WarnStatus.NOT_WARN.toNumber()) {
                    viewHolder.unreadTv.setVisibility(View.VISIBLE);
                    viewHolder.unreadTv.setText("");
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(viewHolder.unreadTv
                            .getLayoutParams());
                    layoutParams.width = 30;
                    layoutParams.height = 30;
                    layoutParams.gravity = Gravity.TOP | Gravity.RIGHT;
                    viewHolder.unreadTv.setLayoutParams(layoutParams);
                } else {
                    viewHolder.unreadTv.setVisibility(View.VISIBLE);
                    FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(-2, -2); //wrap_content
                    layoutParams.gravity = Gravity.TOP | Gravity.RIGHT;
                    viewHolder.unreadTv.setLayoutParams(layoutParams);
                    if (messageEntity.msg_unread_count > 99) {
                        viewHolder.unreadTv.setText("...");
                    } else {
                        viewHolder.unreadTv.setText(String.valueOf(messageEntity.msg_unread_count));
                    }
                }
            }
            if (!TextUtils.isEmpty(messageEntity.msg_last_time)) {
                //最新时间
                viewHolder.timeTv.setText(DateUtils.getMessageList(messageEntity.msg_last_time, DateUtils.FORMAT_1));
            }
            //消息打扰状态
            if (messageEntity.msg_warn_status == MessageEntity.WarnStatus.NOT_WARN.toNumber()) {
                viewHolder.excuseIv.setVisibility(View.VISIBLE);
            } else {
                viewHolder.excuseIv.setVisibility(View.INVISIBLE);
            }
            if (messageEntity.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
                //单聊
                //标题显示
                viewHolder.titleTv.setText(messageEntity.msg_sender_name);
                //内容显示
                if (messageEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
                    //自己发送不成功
                    viewHolder.statusIv.setVisibility(View.VISIBLE);
                    viewHolder.contentTv.setText(messageEntity.msg_content);
                } else {
                    viewHolder.statusIv.setVisibility(View.GONE);
                    viewHolder.contentTv.setText(messageEntity.msg_content);
                }
            } else if (messageEntity.msg_type == MsgType.CHAT_CROUP.toNumber()
                    && messageEntity.group_type == Type.GroupType.TEMP_GROUP) {
                //临时会话
                //标题显示
                viewHolder.titleTv.setText(TextUtils.isEmpty(messageEntity.msg_group_name) ? "未命名" : messageEntity
                        .msg_group_name);
                //内容显示
                if (messageEntity.msg_send_status == MessageEntity.MsgSendStatus.FAILED.toNumber()) {
                    //自己发送不成功
                    viewHolder.statusIv.setVisibility(View.VISIBLE);
                    viewHolder.contentTv.setText(messageEntity.msg_content);
                } else {
                    viewHolder.statusIv.setVisibility(View.GONE);
                    viewHolder.contentTv.setText(messageEntity.msg_content);
                }
            }

            //置顶状态
            LogUtil.d("messageEntity.msg_index>>" + messageEntity.msg_index);
            if (messageEntity.msg_index != 0) {
                viewHolder.relative_bg.setBackgroundColor(mContext.getResources().getColor(R.color.bg_msg_item_top));
            } else {
                viewHolder.relative_bg.setBackgroundColor(mContext.getResources().getColor(R.color.white));
            }
        }

        public static List<Body.NewssnapBean> toJson(String jsonStr) {
            List<Body.NewssnapBean> dataList = new ArrayList<>();
            try {
                JSONObject json = new JSONObject(jsonStr);
                JSONArray jsonArray = json.getJSONArray("newssnap");
                int size = jsonArray.length();
                for (int i = 0; i < size; i++) {
                    Body.NewssnapBean bean = new Body.NewssnapBean();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    bean.setImg(jsonObject.optString("img"));
                    bean.setSrc(jsonObject.optString("src"));
                    bean.setSummary(jsonObject.optString("summary"));
                    bean.setTitle(jsonObject.optString("title"));
                    dataList.add(bean);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return dataList;
        }
    }
}
